package com.dodo.blog.model;

import org.codehaus.jackson.annotate.JsonIgnore;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import java.io.Serializable;
import java.util.Date;

/**
 * @author <a href="mailto:pohorelec@comvai.com">Jozef Pohorelec</a>
 */
@Entity
@MappedSuperclass
public abstract class BaseEntity
        implements Serializable
{
    private static final long serialVersionUID = 1L;

    @Id
    @JsonIgnore
    private Long id;

    private Date updatedDate;

    private Date createdDate;

    /**
     * USE THIS ONLY FOR TESTING PURPOSES!
     *
     * @param id id of entity
     */
    public void setId( Long id )
    {
        this.id = id;
    }

    /**
     * Return id of entity
     *
     * @return id of entity
     */
    public Long getId()
    {
        return id;
    }

    /**
     * Return updated date.
     *
     * @return updated date
     */
    public Date getUpdatedDate()
    {
        return updatedDate;
    }

    /**
     * Date of entity creation
     *
     * @return date of entity creation
     */
    public Date getCreatedDate()
    {
        return createdDate;
    }

    /**
     * Method is called before every update. If entity is updated first time
     * change <code>createdDate</code>, else change <code>updatedDate</code>
     */
    @PrePersist
    @PreUpdate
    public void prePersist()
    {
        if ( id == null )
        {
            createdDate = new Date();
        }
        else
        {
            updatedDate = new Date();
        }
    }
}


